package com.h4313.ghome.io;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.h4313.ghome.R;
import com.h4313.ghome.model.Capteur;
import com.h4313.ghome.utils.UIUtils;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

public class AvailableSourcesTask extends AsyncTask<String, Void, String>{
	
	public interface AvailableSourcesCallback {
		public void onAvailableSourcesFound(HashMap<String, List<Capteur>> capteurs);
	}

	private HashMap<String, List<Capteur>> mCapteursByType;
	private Context mContext;
	private WeakReference<AvailableSourcesCallback> mCallback;
	
	public AvailableSourcesTask(AvailableSourcesCallback callback, Context c) {
		mCallback = new WeakReference<AvailableSourcesCallback>(callback);
		mContext = c;
	}

	@Override
	protected String doInBackground(String... urls) {
		try{
			String contentAsString = NetworkHelper.downloadUrl(urls[0], 60000, 60000);
			mCapteursByType = new HashMap<String, List<Capteur>>();
			JSONObject root = new JSONObject(contentAsString);
			//JSON object contains as keys capteur types, which are required as per the query.
			//Associated to each capteur type, there is an array of ids (of capteurs).
			String[] types = mContext.getResources().getStringArray(R.array.type_capteur);
			for (int i = 0; i < types.length; i++) {
				if (root.has(types[i])) {
					ArrayList<Capteur> capteurs = new ArrayList<Capteur>();
					JSONArray ids = root.getJSONArray(types[i]);
					for (int j = 0; j < ids.length(); j++) {
						Capteur capteur = new Capteur();
						capteur.setIdCapteur(ids.getInt(j));
						capteur.setType(types[i]);
						capteurs.add(capteur);
					}
					mCapteursByType.put(types[i], capteurs);
				}
			}
			return "OK";
		} catch (IOException e){
			System.out.print("Unable to retrieve data. URL may be invalid.");
			e.printStackTrace();
			return null;
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	protected void onPostExecute(String result) {
		if (mCallback.get() != null && result != null) {
			//mCapteurs has been updated during doInBackground()
			mCallback.get().onAvailableSourcesFound(mCapteursByType);
		}
	}

	

}
